<?php

namespace app\index\controller;

use app\admin\model\Jumpurl;
use app\BaseController;
use think\facade\View;

class Index extends BaseController
{

    public function index()
    {
        $params = $this->request->param();
        $href = $this->request->param('href');
        $urlkey = '';
        foreach ($params as $key => $value) {
            $urlkey = $urlkey ? $urlkey : $value;
        }
        $rows = (new Jumpurl())
            ->with(['urlgroup'])
            ->where([
                ['urlkey', '=', $urlkey]
            ])->whereOr([
                ['urlkey', '=', $href]
            ])->find();
        if (empty($urlkey)) {
            $this->error('参数错误');
        }
        if (!$rows) {
            $this->error('链接不存在');
        }
        if ($rows['status'] == 0) {
            $this->error('链接已禁用');
        }
        if ($rows['type'] == 'opt2' && $rows['expired_time'] < time()) {
            $this->error('已过期');
        }
        $groupinfo = $rows['urlgroup'];
        $haystack = $groupinfo['prefix'];
        $needle = $this->request->domain();
        $str_replace = is_array($groupinfo['keywords']) ? $groupinfo['keywords'] : json_decode($groupinfo['keywords'], true);
        $newshowcount = $rows['showcontent'];
        foreach ($str_replace as $rek => $rev) {
            $newshowcount = str_replace($rev['key'], $rev['value'], $newshowcount);
        }
        $rows['showcontent'] = $newshowcount;
        $rows['jumpurl'] = '';
        if (strpos($haystack, $needle) === false) {
            $rows['jumpurl'] = $haystack . $urlkey;
        }
        View::assign([
            'rows' => $rows,
        ]);
        return view('index');
    }

    public function error($msg = '')
    {

        $data = [
            'message' => '错误信息',
            'msg' => '错误信息',
            'data' => ['user_id' => 123]];
        View::assign([
            'rows' => $data,
        ]);
        abort(404, json_encode($data));
    }
}